package com.graduation.check.mapper;

import com.graduation.check.entity.TitleCheckStats;
import com.graduation.check.entity.TitleCheckTask;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface TitleCheckTaskMapper {

    @Insert("INSERT INTO title_check_task (student_id, title, description, check_scope, year_range, max_similarity, " +
            "avg_similarity, duplicate_count, risk_level, check_time, status, duplicate_results, suggestions) " +
            "VALUES (#{studentId}, #{title}, #{description}, #{checkScope}, #{yearRange}, #{maxSimilarity}, " +
            "#{avgSimilarity}, #{duplicateCount}, #{riskLevel}, #{checkTime}, #{status}, #{duplicateResults}, #{suggestions})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(TitleCheckTask task);

    @Select("SELECT * FROM title_check_task WHERE id = #{id}")
    TitleCheckTask findById(Long id);

    @Select("SELECT * FROM title_check_task WHERE student_id = #{studentId} ORDER BY check_time DESC")
    List<TitleCheckTask> findByStudentId(Long studentId);

    @Select("SELECT * FROM title_check_task WHERE student_id = #{studentId} ORDER BY check_time DESC LIMIT #{pageSize} OFFSET #{offset}")
    List<TitleCheckTask> findByStudentIdWithPage(@Param("studentId") Long studentId,
                                                 @Param("offset") int offset,
                                                 @Param("pageSize") int pageSize);

    @Select("SELECT COUNT(*) FROM title_check_task WHERE student_id = #{studentId}")
    Long countByStudentId(Long studentId);

    @Update("UPDATE title_check_task SET max_similarity=#{maxSimilarity}, avg_similarity=#{avgSimilarity}, " +
            "duplicate_count=#{duplicateCount}, risk_level=#{riskLevel}, status=#{status}, " +
            "duplicate_results=#{duplicateResults}, suggestions=#{suggestions} WHERE id=#{id}")
    void update(TitleCheckTask task);



    // 新增：获取学生题目查重统计（真实数据）
    @Select("SELECT COUNT(*) as totalCount, " +
            "COALESCE(MAX(check_time), NOW()) as lastCheckTime " +
            "FROM title_check_task WHERE student_id = #{studentId} AND status = 'COMPLETED'")
    TitleCheckStats findStatsByStudentId(Long studentId);

    // 新增：获取学生最近的题目查重记录（真实数据）
    @Select("SELECT * FROM title_check_task WHERE student_id = #{studentId} AND status = 'COMPLETED' " +
            "ORDER BY check_time DESC LIMIT #{limit}")
    List<TitleCheckTask> findRecentByStudentId(@Param("studentId") Long studentId,
                                               @Param("limit") int limit);
}